#include "head_2.h"

extern linknode *H_trf;
extern linknode *E_trf;

extern linknode *H_sql;
extern linknode *E_sql;

extern void *pthread_buzzer ();	
extern linknode * take_head(linknode *H);

extern pthread_cond_t cond_buzzer;

extern pthread_mutex_t mutex_slinklist;

struct setEnv { 

	int temMAX;
	int temMIN;
	int hunMAX;
	int hunMIN;
	int illMAX;
	int illMIN;

};

extern pthread_mutex_t mutex_analysis;

extern pthread_cond_t cond_analysis;
extern pthread_cond_t cond_sqlite;

extern pthread_mutex_t mutex_linklist;

void *pthread_analysis(){
	
	int shmid;
	int semid;
	key_t key;
	sendEnv *p;
	
	linknode * q;
	
	/*pthread_cond_wait (&cond_analysis, &mutex_analysis);
	pthread_mutex_unlock (&mutex_analysis);*/
	//此条件变量只被激活一次，建议放在while里，解锁放在while后
	//2017.1.17
	//Shrimp7K

	key = ftok("/app",'i');

	if(key < 0){
		perror("fail to ftok");
		exit(1);
	}

	shmid = shmget(key, sizeof(sendEnv), IPC_CREAT|IPC_EXCL|0777);
	
	if(shmid < 0){
		
		if(errno == EEXIST){
			shmid = shmget(key,0,0777);
		}else{
			perror("fail to shmget");
			exit(1);
		}
	}
	
	if ((semid = semget (key, 1, IPC_CREAT | IPC_EXCL |0666)) < 0){
		if (errno == EEXIST){
			semid = semget (key, 1, 0666);
		}
		else{
			perror ("semget");
			exit (-1);
		}
	}
	else{
		init_sem (semid, 0, 1);
	}
	
	if((p =(sendEnv *)shmat(shmid,NULL,0)) == (sendEnv *)-1){
		perror("fail to shmat");
		exit(1);
	}

	while(1){
		
		pthread_mutex_lock (&mutex_analysis);
		pthread_cond_wait (&cond_analysis, &mutex_analysis);//Shrimp7K 2017.1.17
		pthread_mutex_unlock (&mutex_analysis);
		
		usleep(100000);

		printf("start analysis,wait\n");

		/*改动前
		sem_p (semid, 0);
		memcpy(p,&(H->next->env),sizeof(sendEnv));
		sem_v (semid, 0);
		*/
		
		pthread_mutex_lock (&mutex_linklist);
		q = take_head(H_trf);
		pthread_mutex_unlock (&mutex_linklist);
		
		sem_p (semid, 0);
		memcpy(p,&(q->env),sizeof(sendEnv));
		sem_v (semid, 0);
		printf("analysis:%d\n",p->x);
		
		/*
		if ((q->env.x > 15) || (q->env.x < -15) || ((q->env.y > 0) || (q->env.y < -34)) || (q->env.z > 90) || (q->env.z < 65))
		{
			pthread_cond_signal (&cond_buzzer);
		}
		
		pthread_mutex_unlock (&mutex_slinklist);
		head_insert(H_sql, q->env);
		pthread_mutex_unlock (&mutex_slinklist);
		
		pthread_cond_signal (&cond_sqlite);
		
		q = NULL;
		*/

		/*
		if (p->ill > 100)
		{
			if(pthread_create(&id_buzzer, NULL, pthread_buzzer,NULL) < 0)
			{
				perror("pthread_create");
				exit(1);
			}

		}*/
	}
	

}
